package com.ly.hotel.spainterface.jxd.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.spainterface.NmSwipeCardUtils;
import com.ly.hotel.spainterface.OnSwipeCardInterface;
import com.ly.hotel.util.IdChangeUtil;
import com.ly.hotel.util.InterfaceConfUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.view.RoundImageView;
import com.ly.hotel.webagent.UdpCallback;
import com.ly.hotel.webagent.UdpClient;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.ByteArrayInputStream;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import de.greenrobot.event.EventBus;

/**
 * Created by SHUBEN on 2018/3/23.
 */

public class JiShiWorkDialog extends Dialog {
    private Context mcontext;
    private RoundImageView guestSwipe;
    private NmSwipeCardUtils swipUtils;
    private Button backBtn;
    private ImageView loading;
    private ImageView errBill;
    private TextView titleText;
    private LinearLayout workAddArea;
    private TextView workAddCount;
    private ImageButton subBt;
    private ImageButton addBt;
    private Animation alphaAnimation;
    private Animation rotateAnimation;
    private MyApplication app;
    private Handler handler;
    private int funType;
    private String workName;
    private boolean needTip;        // 是否需要小费
    private boolean needEval;       // 是否需要评价
    private Timer mOffTime;
    private TimerTask tt;
    private int countTime;
    private TextView closeText;

    public JiShiWorkDialog(Context context, int theme) {
        super(context, theme);
        mcontext = context;
        app = (MyApplication) mcontext.getApplicationContext();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jishi_work_dialog);

        guestSwipe = findViewById(R.id.guest_swipe);
        backBtn = findViewById(R.id.dialog_back);
        loading = findViewById(R.id.guest_loading);
        titleText = findViewById(R.id.work_swip_title);
        errBill = findViewById(R.id.bill_error);
        workAddArea = findViewById(R.id.work_add_select);
        workAddCount = findViewById(R.id.work_count);
        subBt = findViewById(R.id.work_btn_sub);
        addBt = findViewById(R.id.work_btn_add);
        closeText = findViewById(R.id.work_suc_close);
        subBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int count = Integer.parseInt(workAddCount.getText().toString());
                if(count > 1){
                    workAddCount.setText(count - 1 + "");
                }
            }
        });

        addBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int count = Integer.parseInt(workAddCount.getText().toString());
                if(count < 100){
                    workAddCount.setText(count + 1 + "");
                }else{
                    ToastUtil.showShortToast(mcontext, "单次加钟数不能超过99", 3000);
                }
            }
        });
        alphaAnimation = AnimationUtils.loadAnimation(mcontext, R.anim.alpha_anim);
        rotateAnimation = AnimationUtils.loadAnimation(mcontext, R.anim.rotate_anim);
        mOffTime = new Timer(true);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                dismiss();
            }
        });

        handler = new Handler(){
            public void handleMessage(Message msg){
                loading.clearAnimation();
                loading.setVisibility(View.GONE);
                switch (msg.what){
                    case 0:
                        titleText.setTextColor(mcontext.getResources().getColor(R.color.red));
                        titleText.setText(workName + "失败！\n" + msg.obj.toString());
                        errBill.setImageResource(R.drawable.xf_buy_err);
                        errBill.setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        titleText.setTextColor(mcontext.getResources().getColor(R.color.green));
                        titleText.setText(msg.obj.toString() + workName + "成功！");
                        errBill.setImageResource(R.drawable.xf_buy_suc);
                        errBill.setVisibility(View.VISIBLE);
                        EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_JISHI + "\t" +
                                MyApplication.interfaceVersion + "\t" + workName +"成功"));
                        if(funType == 0 || funType == 2) {
                            showCloseText();
                        }else if(funType == 1){
                            if(!needTip && !needEval){
                                showCloseText();
                            }else{
                                dismiss();
                                TipEvalDialog tipEvalDialog = new TipEvalDialog(mcontext, R.style.InputDialog);
                                tipEvalDialog.setCanceledOnTouchOutside(false);
                                tipEvalDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
                                tipEvalDialog.show();
                                tipEvalDialog.setData(needEval,needTip,msg.obj.toString());
                            }
                        }
                        break;
                    case 99:
                        if(msg.arg1 > 0){
                            closeText.setText(msg.arg1 + " 秒后关闭");
                        }else{
                            dismiss();
                        }
                        break;
                }
            }
        };
        swipUtils =  new NmSwipeCardUtils(new OnSwipeCardInterface() {
            @Override
            public void swipeCardListener(String cardId) {
                String newId = cardId.replaceAll("\r\n", "");
                if(newId.length() == 10) {
                    try {
                        long b = Long.parseLong(newId);
                        guestSwipe.clearAnimation();
                        titleText.setText("Loading...");
                        subBt.setVisibility(View.GONE);
                        addBt.setVisibility(View.GONE);
                        loading.setVisibility(View.VISIBLE);
                        guestSwipe.setVisibility(View.GONE);
                        loading.startAnimation(rotateAnimation);
                        toGetWorkReq(newId);
                    } catch (NumberFormatException e) {
                        Log.e("swipe", "刷卡含有非法字符，重刷！");
                        swipUtils.initSwipe();
                    }
                }else{
                    Log.e("swipe", "刷卡不足10位，重刷！");
                    swipUtils.initSwipe();
                }
            }
        });
    }

    public void initDialog(int type){
        funType = type;
        countTime = 6;
        tt = null;

        workAddCount.setText("1");
        workAddArea.setVisibility(View.GONE);
        if(type == 0){
            workName = "上钟";
        }else if(type == 1){
            workName = "下钟";
        }else{
            workAddArea.setVisibility(View.VISIBLE);
            workName = "加钟";
        }
        titleText.setTextColor(mcontext.getResources().getColor(R.color.orange));
        titleText.setText(workName + "：" + "请刷技师卡");
        loading.clearAnimation();
        guestSwipe.clearAnimation();
        errBill.setVisibility(View.GONE);
        loading.setVisibility(View.GONE);
        closeText.setVisibility(View.GONE);
        guestSwipe.setVisibility(View.VISIBLE);
        addBt.setVisibility(View.VISIBLE);
        subBt.setVisibility(View.VISIBLE);
        swipUtils.initSwipe();
        guestSwipe.startAnimation(alphaAnimation);
    }

    //分析接口上钟、加钟、或下钟
    private void toGetWorkReq(String id){
        if(MyApplication.interfaceVersion.contains("JXD")){
            final String interfaceIp = InterfaceConfUtil.getConf("me","ip","172.16.1.205");
            final String interfacePort = InterfaceConfUtil.getConf("me","port","8081");
            String cardConf = InterfaceConfUtil.getConf("me","cardtype","ID_10");
            if (funType == 1){
                String tip = InterfaceConfUtil.getConf("me","tip","false");
                String eval = InterfaceConfUtil.getConf("me","eval","false");
                if(tip.contains("true")){
                    needTip = true;
                }else{
                    needTip = false;
                }
                if (eval.contains("true")){
                    needEval = true;
                }else{
                    needEval = false;
                }
            }
            final String cardId = IdChangeUtil.getId(id,cardConf);
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    final Message msg = new Message();
                    String request = "";
                    switch (funType) {
                        case 0:
                            request = "<gs ver=\"1.0\" function=\"技师起钟\" mode = \"request\"><ArtNo>" + cardId + "</ArtNo>" +
                                    "<RoomNo></RoomNo><KeyNo></KeyNo><MType></MType><IsSpec></IsSpec><Artpwd></Artpwd></gs>";
                            break;
                        case 1:
                            request = "<gs ver=\"1.0\" function=\"技师落钟\" mode = \"request\"><ArtNo>" + cardId
                                     +"</ArtNo><Artpwd></Artpwd></gs>";
                            break;
                        case 2:
                            request = "<gs ver=\"1.0\" function=\"技师加钟\" mode = \"request\"><ArtNo>" + cardId + "</ArtNo>" +
                                    "<Quantity>" + workAddCount.getText().toString() + "</Quantity><Artpwd></Artpwd></gs>";
                            break;
                        default:
                            break;
                    }
                    Log.d("udp", interfaceIp + "," + interfacePort + "," + request );
                    UdpCallback c = new UdpCallback() {
                        @Override
                        public void receive(String s) {
                            s =  s.replace("\r\n", "").replace("'", "’");
                            if(!TextUtils.isEmpty(s)) {
                                try {
                                    if (!s.startsWith("Msg")) {
                                        DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
                                        DocumentBuilder dombuilder = domfac.newDocumentBuilder();
                                        Document doc = dombuilder.parse(new ByteArrayInputStream(s.getBytes("utf-8")));
                                        NodeList obj = doc.getElementsByTagName("gs");
                                        NodeList rcList = ((Element) obj.item(0)).getElementsByTagName("rc");
                                        NodeList artList = ((Element) obj.item(0)).getElementsByTagName("artno");
                                        NodeList errList = ((Element) obj.item(0)).getElementsByTagName("errmsg");
                                        String rc = "";
                                        String art = "";
                                        String errmsg = "";
                                        if (rcList.getLength() >= 1 && rcList.item(0) != null && rcList.item(0).hasChildNodes()) {
                                            rc = rcList.item(0).getFirstChild().getNodeValue();
                                        }

                                        if (artList.getLength() >= 1 && artList.item(0) != null && artList.item(0).hasChildNodes()) {
                                            art = artList.item(0).getFirstChild().getNodeValue();
                                        }

                                        if (errList.getLength() >= 1 && errList.item(0) != null && errList.item(0).hasChildNodes()) {
                                            errmsg = errList.item(0).getFirstChild().getNodeValue();
                                        }

                                        if(rc.equals("0")){
                                            msg.obj = art;
                                            msg.what = 1;
                                        }else{
                                            msg.obj = art + errmsg;
                                            msg.what = 0;
                                        }
                                    }else {
                                        msg.what=0;
                                        msg.obj = s;
                                    }
                                } catch (Exception e) {
                                    msg.what=0;
                                    msg.obj = "数据解析出错!";
                                }
                            }else {
                                msg.what = 0;
                                msg.obj = mcontext.getString(R.string.connect_err);
                            }
                            handler.sendMessage(msg);
                        }
                    };
                    try {
                        int p = Integer.parseInt(interfacePort);
                        new UdpClient(interfaceIp, p, c, "<gs", "</gs>", "Msg").send(request);
                    } catch (NumberFormatException n) {
                        msg.what=0;
                        msg.obj = "配置出错";
                        handler.sendMessage(msg);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        msg.what=0;
                        msg.obj = "请求出错";
                        handler.sendMessage(msg);
                    }
                }
            }.start();
        }
    }

    @Override
    protected void onStop() {
        if(tt != null) {
            tt.cancel();
        }
        swipUtils.setOnSwipeFlag(false);
        super.onStop();
    }

    private void showCloseText(){
        closeText.setVisibility(View.VISIBLE);
        tt = new TimerTask() {
            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = 99;
                msg.arg1 = countTime;
                handler.sendMessage(msg);
            }
        };
        mOffTime.schedule(tt, 0, 1000);
    }
}